package main.java.service;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import main.java.DAO.IEnrollDAO;
import main.java.constant.StateEnum;
import main.java.model.EnrollContentModel;
import main.java.model.EnrollMetadataModel;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import util.judking.DbHelper;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

@Service("enrollService")
public class EnrollService {
	@Autowired
	@Qualifier("IEnrollDAO")
	private IEnrollDAO enrollDAO;
	@Autowired
	@Qualifier("resourceService")
	ResourceService resourceService;
	@Autowired
	@Qualifier("transactionManager")
	private DataSourceTransactionManager dataSourceTransactionManager;

	// --create
	public StateEnum create(String ripeJson) {
		// begin a transaction for registering to DB
		TransactionStatus status = dataSourceTransactionManager
				.getTransaction(new DefaultTransactionDefinition());
		try {
			EnrollMetadataModel enrollMetadataModel = new EnrollMetadataModel();
			enrollMetadataModel.setName(getValueBySuperKeyFromJson(ripeJson, "enrollName"));
			enrollMetadataModel.setMetadata(ripeJson);
			enrollMetadataModel.setIsOpen(1);
			DbHelper.assertGtZero(enrollDAO.insertMetadata(enrollMetadataModel));

			dataSourceTransactionManager.commit(status);
			return StateEnum.SUCCESS;
		} catch (RuntimeException e) {
			dataSourceTransactionManager.rollback(status);
			throw e;
		}
	}

	public String formatJson(String rawJson) {
		Pattern pattern = Pattern.compile("\\{.*\\}");
		Matcher matcher = pattern.matcher(rawJson);
		if (matcher.find()) {
			return matcher.group();
		}
		throw new RuntimeException(
				"EnrollService.formatJson: not in json format: " + rawJson);
	}

	public String getValueBySuperKeyFromJson(String json, String key) {
		Gson gson = new Gson();
		Map<String, String> map = new HashMap<>();
		map = gson.fromJson(json, map.getClass());
		return map.get(key);
	}

	// --createImg
	public String createImg(CommonsMultipartFile img, String servletPath)
			throws IOException {
		String enrollImgDirectory = resourceService.getCurrentWebappRootPath()
				+ servletPath;
		String name = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
				+ "."
				+ resourceService
						.getFileNameSuffix(img.getFileItem().getName());

		File enrollImgFile = resourceService.genFile(name, enrollImgDirectory);
		byte[] data = img.getFileItem().get();
		resourceService.writeToFile(enrollImgFile, data, false);
		return enrollImgFile.toString();
	}

	public StateEnum submit(String ripeJson) {
		// begin a transaction for registering to DB
		TransactionStatus status = dataSourceTransactionManager
				.getTransaction(new DefaultTransactionDefinition());
		try {
			EnrollContentModel enrollContentModel = new EnrollContentModel();
			enrollContentModel.setMetadata_id(getValueBySuperKeyFromJson(ripeJson, "metadata_id"));
			enrollContentModel.setContent(ripeJson);
			DbHelper.assertGtZero(enrollDAO.insertContent(enrollContentModel));

			dataSourceTransactionManager.commit(status);
			return StateEnum.SUCCESS;
		} catch (RuntimeException e) {
			dataSourceTransactionManager.rollback(status);
			throw e;
		}
	}
}
